package com.reliable.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reliable.api.dto.template.ReliableAnalysisTemplateDTO;
import com.reliable.api.param.template.ReliableAnalysisTemplatePageParam;
import com.reliable.api.param.template.ReliableAnalysisTemplateParam;
import com.reliable.api.param.IdParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.common.core.page.TableDataInfo;
import com.reliable.service.domain.ReliableAnalysisTemplate;
import com.reliable.service.service.IReliableAnalysisTemplateService;
import com.reliable.service.utils.IdEncryptUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分析模板Controller
 *
 * @author ruoyi
 * @date 2025-11-18
 */
@RestController
@RequestMapping("/reliable/template")
@Api(tags = "分析模板管理")
@Validated
public class ReliableAnalysisTemplateController {

    @Autowired
    private IReliableAnalysisTemplateService reliableAnalysisTemplateService;

    /**
     * 查询分析模板列表
     */
    @ApiOperation("查询分析模板列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody ReliableAnalysisTemplatePageParam param) {
        Page<ReliableAnalysisTemplateDTO> page = new Page<>(param.getPageNum(), param.getPageSize());

        // 执行分页查询（包含关键词文本）
        IPage<ReliableAnalysisTemplateDTO> result = reliableAnalysisTemplateService.selectTemplateListWithKeywords(
                page,
                param.getTemplateName(),
                param.getTemplateType(),
                param.getRiskLevel(),
                param.getIsActive()
        );

        // 转换为DTO并加密ID
        List<ReliableAnalysisTemplateDTO> records = result.getRecords().stream().map(template -> {
            ReliableAnalysisTemplateDTO dto = new ReliableAnalysisTemplateDTO();
            // 复制除keywordText外的所有属性
            dto.setId(IdEncryptUtils.encrypt(Long.valueOf(template.getId())));
            dto.setTemplateName(template.getTemplateName());
            dto.setTemplateCode(template.getTemplateCode());
            dto.setTemplateDescription(template.getTemplateDescription());
            dto.setTemplateType(template.getTemplateType());
            dto.setRiskLevel(template.getRiskLevel());
            dto.setIsActive(template.getIsActive());
            dto.setMatchLogic(template.getMatchLogic());
            dto.setAiPromptTemplate(template.getAiPromptTemplate());
            if (template.getKeywordId() != null) {
                dto.setKeywordId(IdEncryptUtils.encrypt(template.getKeywordId()));
            }
            dto.setKeywordText(template.getKeywordText());
            dto.setCreateTime(template.getCreateTime());
            dto.setUpdateTime(template.getUpdateTime());
            return dto;
        }).collect(Collectors.toList());

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(records);
        tableDataInfo.setTotal(result.getTotal());
        return tableDataInfo;
    }
    /**
     * 获取分析模板详细信息
     */
    @ApiOperation("获取分析模板详细信息")
    @PostMapping(value = "/info")
    public AjaxResult getInfo(@Valid @RequestBody IdParam idParam) {
        Long decryptId = IdEncryptUtils.decrypt(idParam.getId().toString());
        ReliableAnalysisTemplate template = reliableAnalysisTemplateService.getById(decryptId);
        if (template != null) {
            ReliableAnalysisTemplateDTO dto = new ReliableAnalysisTemplateDTO();
            BeanUtils.copyProperties(template, dto);
            dto.setId(IdEncryptUtils.encrypt(template.getId()));
            if (template.getKeywordId() != null) {
                dto.setKeywordId(IdEncryptUtils.encrypt(template.getKeywordId()));
            }
            return AjaxResult.success(dto);
        } else {
            return AjaxResult.error("未找到该分析模板");
        }
    }

    /**
     * 新增分析模板
     */
    @ApiOperation("新增分析模板")
    @PostMapping("/add")
    public AjaxResult add(@Valid @RequestBody ReliableAnalysisTemplateParam param) {
        ReliableAnalysisTemplate template = new ReliableAnalysisTemplate();
        BeanUtils.copyProperties(param, template);
        // 解密keywordId
        if (param.getKeywordId() != null && !param.getKeywordId().isEmpty()) {
            template.setKeywordId(IdEncryptUtils.decrypt(param.getKeywordId()));
        }

        return AjaxResult.success(reliableAnalysisTemplateService.save(template));
    }

    /**
     * 修改分析模板
     */
    @ApiOperation("修改分析模板")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody ReliableAnalysisTemplateParam param) {
        ReliableAnalysisTemplate template = new ReliableAnalysisTemplate();
        BeanUtils.copyProperties(param, template);
        // 解密ID和keywordId
        template.setId(IdEncryptUtils.decrypt(param.getId()));
        if (param.getKeywordId() != null && !param.getKeywordId().isEmpty()) {
            template.setKeywordId(IdEncryptUtils.decrypt(param.getKeywordId()));
        }
        return AjaxResult.success(reliableAnalysisTemplateService.updateById(template));
    }

    /**
     * 删除分析模板
     */
    @ApiOperation("删除分析模板")
    @PostMapping("/remove")
    public AjaxResult remove(@Valid @RequestBody IdParam idParam) {
        Long decryptId = IdEncryptUtils.decrypt(idParam.getBusinessId());
        boolean result = reliableAnalysisTemplateService.removeById(decryptId);
        return AjaxResult.success(result ? "删除成功" : "删除失败");
    }
}